<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品专区" prop="productArea">
        <el-select
          v-model="queryParams.productArea"
          placeholder="请选择商品专区"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in productAreaList"
            :key="dict.areaId"
            :label="dict.areaName"
            :value="dict.areaId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品分类" prop="productCate">
        <el-select
          v-model="queryParams.productCate"
          placeholder="请选择商品分类"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in productCateList"
            :key="dict.cateId"
            :label="dict.cateName"
            :value="dict.cateId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="广告等级" prop="advertLevel">
        <el-select
          v-model="queryParams.advertLevel"
          placeholder="请选择广告等级"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in levelListData"
            :key="dict.levelId"
            :label="dict.levelName"
            :value="dict.levelId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tabelData">
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="expandBox">
            <el-table v-loading="loading" :data="props.row.skuList">
              <el-table-column
                label="规格"
                align="center"
                prop="specValue"
                width="200"
              />
              <el-table-column
                label="封面图"
                align="center"
                :show-overflow-tooltip="true"
                width="150"
              >
                <template slot-scope="scope">
                  <el-image
                    :src="scope.row.pic"
                    :preview-src-list="[scope.row.pic]"
                    style="width: 60px; height: 60px"
                  ></el-image>
                </template>
              </el-table-column>
              <el-table-column
                label="售价"
                align="center"
                prop="platformPrice"
              />
              <el-table-column
                label="划线价"
                align="center"
                prop="productPrice"
              />
              <el-table-column label="成本价" align="center" prop="costPrice" />
              <el-table-column label="库存" align="center" prop="inventory" />
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品排序"
        align="center"
        prop="sort"
        width="120"
      />
      <el-table-column
        label="商品ID"
        align="center"
        prop="productId"
        width="120"
      />
      <el-table-column
        label="商品名称"
        align="center"
        prop="productName"
        width="200"
      />
      <el-table-column
        label="封面图"
        align="center"
        :show-overflow-tooltip="true"
        width="150"
      >
        <template slot-scope="scope">
          <el-image
            :src="scope.row.mainImageUrl"
            :preview-src-list="[scope.row.mainImageUrl]"
            style="width: 60px; height: 60px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="cateName" />
      <el-table-column label="首页展示" align="center" prop="showIndexFlag">
        <template slot-scope="scope">
          <span v-if="scope.row.showIndexFlag">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="商品专区" align="center" prop="productArea">
        <template slot-scope="scope">
          <div v-for="(item, index) in productAreaList" :key="index">
            <span v-if="item.areaId == scope.row.productArea">{{
              item.areaName
            }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="广告收益等级" align="center" prop="advertLevel">
        <template slot-scope="scope">
          <div v-if="scope.row.advertLevel">
            {{ scope.row.advertLevel | getLabel(levelListData) }}
          </div>
          <div v-else>无</div>
        </template>
      </el-table-column>
      <el-table-column label="商品状态" align="center" prop="productStatus">
        <template slot-scope="scope">
          <div v-for="(item, index) in productStatusList" :key="index">
            <span v-if="item.value == scope.row.productStatus">{{
              item.label
            }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <editProduct
      ref="editProduct"
      :title="title"
      :form="form"
      @update="getList"
      @reset="reset"
      :productAreaList="productAreaList"
      :levelListData="levelListData"
      :productStatusList="productStatusList"
      :productTypeList="productTypeList"
    ></editProduct>
  </div>
</template>

<script>
import {
  productList,
  insertProduct,
  detailProduct,
  modifyProduct,
  delProduct,
} from "@/api/product/product";
import { userLevelList } from "@/api/customer/customer";
import { productCateList } from "@/api/product/productCate";
import { productAreaList } from "@/api/product/productArea";
import editProduct from "./editProduct";
import { Debounce } from "@/utils/tools.js";
import store from "@/store";
export default {
  name: "product",
  dicts: ["sys_normal_disable"],
  components: {
    editProduct,
  },
  data() {
    return {
      productArea: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tabelData: [],
      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        productName: null,
        productArea: null,
        advertLevel: null,
      },
      // 表单参数
      form: {},
      productCateList: [],
      productAreaList: [],
      levelListData: [],
      productStatusList: [
        { label: "待审核", value: 1 },
        { label: "审核中", value: 2 },
        { label: "已上架", value: 3 },
        { label: "已下架", value: 4 },
      ],
      productTypeList: [
        { label: "实物商品", value: "real" },
        { label: "话费快充商品", value: "call" },
        { label: "话费慢充商品", value: "call_slow" },
        { label: "卡密商品", value: "coupon" },
        { label: "直充商品", value: "recharge" },
        { label: "流量商品", value: "flow" },
        { label: "赠送商品", value: "gift" },
        { label: "电费慢充", value: "electricity_fees_slow" },
      ],
      rolesBool: false,
    };
  },
  filters: {
    getLabel(e, arr) {
      let label = "";
      let arra = arr.filter((item) => e == item.levelId);
      if (arra.length) {
        label = arra[0].levelName;
      }
      return label;
    },
  },
  created() {
    this.getList();
    this.getProductCateList();
    this.getProductAreaList();
    this.getLevelList();
    this.rolesBool = this.$store.state.user.roles.indexOf("admin") !== -1;
  },
  methods: {
    getLevelList() {
      userLevelList().then((res) => {
        if (res.code == 200) {
          this.levelListData = res.data.records;
        }
      });
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      productList(this.queryParams).then((response) => {
        response.data.records.forEach((item) => {
          if (item.skuList && item.skuList.length > 0) {
            item.hasChildren = true;
          } else {
            item.hasChildren = false;
          }
        });
        this.tabelData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
        console.log(this.tabelData, "this.tabelData");
      });
    },
    // 查询商品分类列表
    getProductCateList() {
      productCateList({ pageNo: 1, pageSize: 200 }).then((response) => {
        this.productCateList = response.data.records;
      });
    },
    // 查询商品专区列表
    getProductAreaList() {
      productAreaList({ pageNo: 1, pageSize: 200 }).then((response) => {
        this.productAreaList = response.data.records;
      });
    },
    /** 新增按钮操作 */
    handleAdd: Debounce(function (e) {
      this.reset();
      this.form = {
        showIndexFlag: null,
        mainImageUrl: [],
        productImageUrl: [],
      };
      this.$refs.editProduct.edit = false;
      this.$refs.editProduct.open = true;
      this.$refs.editProduct.specNew = [];
      this.$refs.editProduct.skuList = [
        {
          skuName: "", //规格名
          specValue: "", //规格值
          pic: [], //图片
          platformPrice: "", //售价
          productPrice: "",
          costPrice: "", //成本
          unit: "", //单位
          publishStatus: "1", //上下架状态: (1-已上架 2-已下架)
          inventory: "", //库存
          expressType: "2", //快递类型 1 到付、2 包邮，默认到付
          buyCount: "", //起售量
          limitedCount: "", //限购量
        },
      ];
      this.title = "添加商品";
    }, 500),
    /** 修改按钮操作 */
    handleUpdate: Debounce(function (row) {
      this.reset();
      detailProduct(row.productId).then((response) => {
        this.form = response.data;
        this.form.mainImageUrl = [{ url: this.form.mainImageUrl }];
        if (this.form.productImageUrl && this.form.productImageUrl.length > 0) {
          this.form.productImageUrl = this.form.productImageUrl.map((item) => {
            return { url: item };
          });
        }
        // 编辑sku数据格式化
        this.form.skuList.forEach((item) => {
          item.pic = [{ url: item.pic }];
          item.publishStatus = item.publishStatus.toString();
          item.expressType = item.expressType.toString();
        });
        // 规格
        let objSpecs = {};
        let arr = [];
        if (this.form.skuList.length) {
          this.form.skuList.forEach((item) => {
            let obj = {
              specValueName: item.specValue,
            };
            arr.push(obj);
            objSpecs.specNewName = item.skuName;
          });
          objSpecs.specNewValue = arr;
        }
        this.$refs.editProduct.skuList = this.form.skuList;
        this.$refs.editProduct.specNew = [objSpecs];
        this.$refs.editProduct.edit = true;
        this.$refs.editProduct.open = true;
        this.title = "修改商品";
      });
    }, 500),
    /** 删除按钮操作 */
    handleDelete: Debounce(function (row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.productName + '"的数据项？')
        .then(function () {
          return delProduct(row.productId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    }, 500),
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.storeId = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 提交按钮 */
    submitForm: Debounce(function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let data = {
            orderId: this.form.orderId,
            deliverName: this.form.deliverName,
            deliverNo: this.form.deliverNo,
          };
          changeWallet(data).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.getList();
          });
        }
      });
    }, 500),
  },
};
</script>
<style lang="scss" scoped>
.expandBox {
  padding: 20px 30px;
  box-sizing: border-box;
}
</style>
